<script setup lang="ts">
import {InfoCircleOutlined} from "@ant-design/icons-vue";
import {WxtBizCode, WxtUtils} from "~/contentScripts/views/wxt/lib/wxtUtils";

const props = defineProps({
  value: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  rows: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: WxtBizCode.关键字推广,
  },
});
const emit = defineEmits([
  "update:value",
]);
const KeywordTypeEnum = {
  综合推荐词: 'kr_overall',
  精准引流词: 'kr_flow',
  类目优选词: 'kr_category',
  行业机会词: 'kr_industry',
};
const data = reactive({
  switchValue: true,
  number: 20,
  relevance: 'good',
  titleMustIncludeKeyword: false,
  keywordIncludeText: '',
  allKeywordNotRepeat: false,
  keywordNotIncludeText: '',
  keywordType: [KeywordTypeEnum.综合推荐词],
  // 点击率区间
  clickRateRange: {
    min: undefined,
    max: undefined,
  },
  // 点击转化率区间
  clickConversionRateRange: {
    min: undefined,
    max: undefined,
  },
  // 市场平均出价区间
  marketAverageBidRange: {
    min: undefined,
    max: undefined,
  },
  // 进店次数区间
  enterStoreCountRange: {
    min: undefined,
    max: undefined,
  },
  // 下单转化率区间
  orderConversionRateRange: {
    min: undefined,
    max: undefined,
  },
  // 引导下单数区间
  guideOrderCountRange: {
    min: undefined,
    max: undefined,
  },
  // 搜索指数区间
  searchIndexRange: {
    min: undefined,
    max: undefined,
  },
  // 预估展现量区间
  estimateShowCountRange: {
    min: undefined,
    max: undefined,
  },
  // 竞争指数区间
  competitionIndexRange: {
    min: undefined,
    max: undefined,
  },
});
const keywordsResponse = reactive<any>({
  kr_overall: {},
  kr_flow: {},
  kr_category: {},
  kr_industry: {},
});
const loadKeywords = (materialId: number | undefined = undefined, campaignId: number | undefined = undefined, adgroupId: number | undefined = undefined) => {
  data.keywordType.map((item: any) => {
    const key = getKey({
      itemId: materialId,
      campaignId: campaignId,
      adgroupId: adgroupId,
    });
    // 如果已有此数据则不再请求
    if (typeof keywordsResponse[item][key] !== 'undefined') {
      return;
    }
    WxtUtils.customRequest('https://one.alimama.com/bidword/suggest/kr/list.json', props.bizCode, {
      materialId: materialId,
      campaignId: campaignId,
      adgroupId: adgroupId,
      type: item,
    }).then(res => {
      keywordsResponse[item][key] = res.data.data.list;
      change();
    });
  });
}
onMounted(() => {
  props.rows.map((item: any) => {
    if (typeof item.campaignId !== 'undefined' && typeof item.adgroupId !== 'undefined') {
      loadKeywords(item.material.materialId, item.campaignId, item.adgroupId);
    } else {
      loadKeywords(item.itemId);
    }
  });
});
watch(() => props.rows, (val) => {
  val.map((item: any) => {
    if (typeof item.campaignId !== 'undefined' && typeof item.adgroupId !== 'undefined') {
      loadKeywords(item.material.materialId, item.campaignId, item.adgroupId);
    } else {
      loadKeywords(item.itemId);
    }
  });
}, {
  deep: true,
});
watch(() => data, (val) => {
  change();
}, {
  deep: true,
});
watch(() => data.keywordType, (val) => {
  props.rows.map((item: any) => {
    if (typeof item.campaignId !== 'undefined' && typeof item.adgroupId !== 'undefined') {
      loadKeywords(item.material.materialId, item.campaignId, item.adgroupId);
    } else {
      loadKeywords(item.itemId);
    }
  });
}, {
  deep: true,
});
const getKey = (item: any) => {
  let key = item.itemId || '';
  if (typeof item.campaignId !== 'undefined' && typeof item.adgroupId !== 'undefined') {
    key = (item.campaignId || '') + '-' + (item.adgroupId || '');
  }
  return key;
}
const change = () => {
  if (!data.switchValue) {
    emit('update:value', props.rows.map((item: any) => {
      return {
        [getKey(item)]: [],
      };
    }));
  } else {
    //{itemId:[]}
    let dd: any = {};
    props.rows.map((item: any) => {
      let d: any[] = [];
      let key = getKey(item);
      data.keywordType.map((type: any) => {
        console.log(type);
        if (typeof keywordsResponse[type][key] !== 'undefined') {
          d = d.concat(keywordsResponse[type][key]);
        }
      });
      console.log(keywordsResponse);
      console.log(d);
      // 去重
      d = Array.from(new Set(d));
      //标题必须包括关键词
      if (data.titleMustIncludeKeyword) {
        d = d.filter((it: any) => {
          return item.title.includes(it.word);
        });
      }
      // 关键词包含文本
      if (data.keywordIncludeText) {
        const keywordIncludeTextArr = data.keywordIncludeText.split(' ');
        d = d.filter((it: any) => {
          return keywordIncludeTextArr.every((text: string) => {
            return it.word.includes(text);
          });
        });
      }
      // 关键词不包含文本
      if (data.keywordNotIncludeText) {
        const keywordNotIncludeTextArr = data.keywordNotIncludeText.split(' ');
        d = d.filter((it: any) => {
          return keywordNotIncludeTextArr.every((text: string) => {
            return !it.word.includes(text);
          });
        });
      }
      // 市场平均出价区间
      if (typeof data.marketAverageBidRange.min !== 'undefined') {
        d = d.filter((it: any) => {
          return it.bidPrice >= data.marketAverageBidRange.min
        });
      }
      if (typeof data.marketAverageBidRange.max !== 'undefined') {
        d = d.filter((it: any) => {
          return it.bidPrice <= data.marketAverageBidRange.max
        });
      }
      // 点击率区间
      if (typeof data.clickRateRange.min !== 'undefined') {
        d = d.filter((it: any) => {
          return it.ctr * 100 >= data.clickRateRange.min;
        });
      }
      if (typeof data.clickRateRange.max !== 'undefined') {
        d = d.filter((it: any) => {
          return it.ctr * 100 <= data.clickRateRange.max;
        });
      }
      // 点击转化率区间
      if (typeof data.clickConversionRateRange.min !== 'undefined') {
        d = d.filter((it: any) => {
          return it.cvr * 100 >= data.clickConversionRateRange.min;
        });
      }
      if (typeof data.clickConversionRateRange.max !== 'undefined') {
        d = d.filter((it: any) => {
          return it.cvr * 100 <= data.clickConversionRateRange.max;
        });
      }
      // //下单转化率区间
      if (typeof data.orderConversionRateRange.min !== 'undefined') {
        d = d.filter((it: any) => {
          return it.convRatio * 100 >= data.orderConversionRateRange.min;
        });
      }
      if (typeof data.orderConversionRateRange.max !== 'undefined') {
        d = d.filter((it: any) => {
          return it.convRatio * 100 <= data.orderConversionRateRange.max;
        });
      }
      //统一商品关键词不重复 所有word不重复
      if (data.allKeywordNotRepeat) {
        d = d.filter((it: any) => {
          return !Object.values(dd).flat().map((item: any) => it.word).includes(it.word);
        });
      }
      //相关性
      if (data.relevance === 'good') {
        d = d.filter((it: any) => {
          return it.relevanceType === 3;
        });
      } else if (data.relevance === 'middle') {
        d = d.filter((it: any) => {
          return it.relevanceType === 2;
        });
      } else if (data.relevance === 'bad') {
        d = d.filter((it: any) => {
          return it.relevanceType === 1;
        });
      }
      if (d.length > data.number) {
        d = d.slice(0, data.number);
      }
      dd[getKey(item)] = d;
    });
    emit('update:value', dd);
  }
}
// const loadNumber = computed(() => {
//   let number = 0;
//   data.keywordType.map((type: any) => {
//     if(typeof keywordsResponse[type].map === 'undefined'){
//       return;
//     }
//     keywordsResponse[type].map((item: any) => {
//       number += item.length;
//     });
//   });
//   return number;
// });
// const loadKeywordsString = computed(() => {
//   let str = '';
//   data.keywordType.map((type: any) => {
//     if(typeof keywordsResponse[type].map === 'undefined'){
//       return;
//     }
//     str += keywordsResponse[type].map((item: any) => {
//       return item.map((it: any) => {
//         return it.word;
//       }).join(',');
//     });
//   });
//   return str;
// });
</script>

<template>
  <div class="box">
    <div class="title">
      <a-row type="flex">
        <a-col flex="1">
          <span class="bold">自动添加关键词配置</span>
          <a-tooltip title="获取官方推荐词, 按设定的条件筛选添加">
            <InfoCircleOutlined/>
          </a-tooltip>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <span class="gray">自动添加关键字: </span>
          <a-switch v-model:checked="data.switchValue" size="small"/>
        </a-col>
        <!--        <a-col style="color: #666;font-size: 14px;">-->
        <!--          <a-tooltip :title="loadKeywordsString">-->
        <!--            已载入个<span style="color: #ff4d4f">{{ loadNumber }}</span>个关键词-->
        <!--          </a-tooltip>-->
        <!--        </a-col>-->
      </a-row>
    </div>
    <div class="content">
      <div class="mask" v-if="!data.switchValue">
        <InfoCircleOutlined/>&nbsp;&nbsp;不需要自动添加关键词
      </div>
      <a-row type="flex">
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>关键词数量: </span>
            </a-col>
            <a-col :span="13">
              <a-input-number v-model:value="data.number" min="0" max="200" size="small" style="width: 100px;"/>
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="12">
          <!--          相关性：好-中-差-->
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>相关性: </span>
            </a-col>
            <a-col :span="13">
              <a-select v-model:value="data.relevance" size="small" style="width: 120px;">
                <a-select-option value="good">好</a-select-option>
                <a-select-option value="middle">中</a-select-option>
                <a-select-option value="bad">差</a-select-option>
              </a-select>
            </a-col>
          </a-row>
        </a-col>
      </a-row>

      <!--        标题必须包括关键词开关 和 关键词包含文本开关-->
      <a-row type="flex">
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>标题必须包括关键词: </span>
            </a-col>
            <a-col :span="13">
              <a-switch v-model:checked="data.titleMustIncludeKeyword" size="small"/>
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>关键词包含文本: </span>
            </a-col>
            <a-col :span="13">
              <a-input v-model:value="data.keywordIncludeText" size="small" style="width: 100%;"
                       placeholder="多个空格分隔"
              />
            </a-col>
          </a-row>
        </a-col>
      </a-row>
      <!--      统一商品关键词不重复 和 关键词不包含文本-->
      <a-row type="flex">
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>统一商品关键词不重复: </span>
            </a-col>
            <a-col :span="13">
              <a-switch v-model:checked="data.allKeywordNotRepeat" size="small"/>
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>关键词不包含文本: </span>
            </a-col>
            <a-col :span="13">
              <a-input v-model:value="data.keywordNotIncludeText" size="small" style="width: 100%;"
                       placeholder="多个空格分隔"
              />
            </a-col>
          </a-row>
        </a-col>
      </a-row>
      <!--      关键词 类型-->
      <a-row type="flex">
        <a-col style="text-align: right;padding-right:10px;width: calc(50% / 24 * 11)">
          <span>关键词类型: </span>
        </a-col>
        <a-col flex="1">
          <!--          多选 综合推荐词 精准引流词 类目优选词 行业机会词 -->
          <a-checkbox-group v-model:value="data.keywordType" size="small">
            <a-checkbox v-for="item in Object.keys(KeywordTypeEnum)"
                        :disabled="data.keywordType.length==1 && data.keywordType.includes(KeywordTypeEnum[item])"
                        :key="item" :value="KeywordTypeEnum[item]"
            >
              {{ item }}
            </a-checkbox>
          </a-checkbox-group>
        </a-col>
      </a-row>
      <!--      点击率区间和点击转化率区间-->
      <a-row type="flex">
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>点击率区间: </span>
            </a-col>
            <a-col :span="13">
              <a-input-number :min="0" :max="100" v-model:value="data.clickRateRange.min" size="small"
                              style="width: 80px;" placeholder="最小值"
              />
              -
              <a-input-number :min="0" :max="100" v-model:value="data.clickRateRange.max" size="small"
                              style="width: 80px;" placeholder="最大值"
              />
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>点击转化率区间: </span>
            </a-col>
            <a-col :span="13">
              <a-input-number :min="0" :max="100" v-model:value="data.clickConversionRateRange.min" size="small"
                              style="width: 80px;" placeholder="最小值"
              />
              -
              <a-input-number :min="0" :max="100" v-model:value="data.clickConversionRateRange.max" size="small"
                              style="width: 80px;" placeholder="最大值"
              />
            </a-col>
          </a-row>
        </a-col>
      </a-row>
      <!--      市场平均出价区间和进店次数区间-->
      <a-row type="flex">
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>市场平均出价区间: </span>
            </a-col>
            <a-col :span="13">
              <a-input-number :min="0" v-model:value="data.marketAverageBidRange.min" size="small" style="width: 80px;"
                              placeholder="最小值"
              />
              -
              <a-input-number :min="0" v-model:value="data.marketAverageBidRange.max" size="small" style="width: 80px;"
                              placeholder="最大值"
              />
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>进店次数区间: </span>
            </a-col>
            <a-col :span="13">
              <a-input-number :min="0" v-model:value="data.enterStoreCountRange.min" size="small" style="width: 80px;"
                              placeholder="最小值"
              />
              -
              <a-input-number :min="0" v-model:value="data.enterStoreCountRange.max" size="small" style="width: 80px;"
                              placeholder="最大值"
              />
            </a-col>
          </a-row>
        </a-col>
      </a-row>

      <!--          下单转化率区间和引导下单数区间-->
      <a-row type="flex">
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>下单转化率区间: </span>
            </a-col>
            <a-col :span="13">
              <a-input-number :min="0" :max="100" v-model:value="data.orderConversionRateRange.min" size="small"
                              style="width: 80px;" placeholder="最小值"
              />
              -
              <a-input-number :min="0" :max="100" v-model:value="data.orderConversionRateRange.max" size="small"
                              style="width: 80px;" placeholder="最大值"
              />
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>引导下单数区间: </span>
            </a-col>
            <a-col :span="13">
              <a-input-number :min="0" v-model:value="data.guideOrderCountRange.min" size="small" style="width: 80px;"
                              placeholder="最小值"
              />
              -
              <a-input-number :min="0" v-model:value="data.guideOrderCountRange.max" size="small" style="width: 80px;"
                              placeholder="最大值"
              />
            </a-col>
          </a-row>
        </a-col>
      </a-row>
      <!--      搜索指数区间和预估展现量区间-->
      <a-row type="flex">
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>搜索指数区间: </span>
            </a-col>
            <a-col flex="1">
              <a-input-number :min="0" v-model:value="data.searchIndexRange.min" size="small" style="width: 80px;"
                              placeholder="最小值"
              />
              -
              <a-input-number :min="0" v-model:value="data.searchIndexRange.max" size="small" style="width: 80px;"
                              placeholder="最大值"
              />
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>预估展现量区间: </span>
            </a-col>
            <a-col flex="1">
              <a-input-number :min="0" v-model:value="data.estimateShowCountRange.min" size="small" style="width: 80px;"
                              placeholder="最小值"
              />
              -
              <a-input-number :min="0" v-model:value="data.estimateShowCountRange.max" size="small" style="width: 80px;"
                              placeholder="最大值"
              />
            </a-col>
          </a-row>
        </a-col>
      </a-row>
      <!--      竞争指数区间-->
      <a-row type="flex">
        <a-col :span="12">
          <a-row type="flex" align="middle">
            <a-col :span="11" style="text-align: right;padding-right:10px;">
              <span>竞争指数区间: </span>
            </a-col>
            <a-col flex="1">
              <a-input-number :min="0" v-model:value="data.competitionIndexRange.min" size="small" style="width: 80px;"
                              placeholder="最小值"
              />
              -
              <a-input-number :min="0" v-model:value="data.competitionIndexRange.max" size="small" style="width: 80px;"
                              placeholder="最大值"
              />
            </a-col>
          </a-row>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<style lang="less" scoped>
.box {
  border: #eee solid 1px;
  border-radius: 10px;
  overflow: hidden;
}

.title {
  background-color: #ebeef5;
  padding: 10px;
  line-height: 28px;

  .bold {
    font-weight: bold;
    color: #444;
  }

  .gray {
    color: #555;
  }
}

.content {
  color: #222;
  position: relative;

  .mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, .9);
    color: #ff4d4f;
    //opacity: 0.5;
    z-index: 1;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  > div {
    padding: 10px;
    border-bottom: #eee solid 1px;

    &:last-child {
      border-bottom: none;
    }

    .ant-row {
      height: 30px;
      line-height: 30px;

      .ant-col {
        height: 30px;
        line-height: 30px;
        color: #444;
      }
    }
  }
}
</style>
